package com.sc.nft.admin.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.sc.nft.admin.request.*;
import com.sc.nft.annotation.SysMemberLogin;
import com.sc.nft.entity.GxequityRecords;
import com.sc.nft.entity.SysMember;
import com.sc.nft.entity.dto.BatchEnterIntegrationDTO;
import com.sc.nft.entity.vo.*;
import com.sc.nft.enums.AssetChangeLogEnum;
import com.sc.nft.enums.CoinCategoryEnum;
import com.sc.nft.enums.RedisKeyEnum;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.pool.SysMemberPool;
import com.sc.nft.service.UserAssetsService;
import com.sc.nft.sup.PageResult;
import com.sc.nft.sup.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpPost;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 菜单表服务控制器
 *
 * @author rdg
 * @since 2022-06-05
 * @description
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/admin/userAssets")
@Api(tags="用户积分")
public class UserAssetsController {
    private final UserAssetsService userAssetsService;
    private final Redisson redisson;
    @PostMapping(value="/userAssetsList", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取用户积分列表",notes="获取用户积分列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public PageResult<UserAssetsVO> userAssetsList(@Valid @RequestBody PageUserAssetsRequest pageUserAssetsRequest){
       Page page= userAssetsService.pageUserAssetsList(pageUserAssetsRequest.getUserUuid(),pageUserAssetsRequest.getNickName(), pageUserAssetsRequest.getUserTel(), pageUserAssetsRequest.getPageNo(),pageUserAssetsRequest.getPageSize());
       return PageResult.success(page,UserAssetsVO.class);
    }

    @PostMapping(value="/assetsChangeList", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "用户积分变动记录",notes="获取用户积分列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public PageResult<AssetsChangeListVO> assetsChangeList(@Valid @RequestBody AssetsChangeRequest assetsChangeRequest){
        Page page= userAssetsService.pageAssetsChangeList(assetsChangeRequest.getUserId(),assetsChangeRequest.getType(),assetsChangeRequest.getStartDate(),assetsChangeRequest.getEndDate(),assetsChangeRequest.getPageNo(),assetsChangeRequest.getPageSize());
        return PageResult.success(page,AssetsChangeListVO.class);
    }
    @PostMapping(value="/userExchangeRecord", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "用户积分兑换记录",notes="用户积分兑换记录", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public PageResult<AdminUserExchangeRecordVO> userExchangeRecord(@Valid @RequestBody UserExchangeRecordRequest userExchangeRecordRequest){
        Page page= userAssetsService.pageUserExchangeRecord(userExchangeRecordRequest.getUserId(),userExchangeRecordRequest.getTypeClassify(),userExchangeRecordRequest.getStartDate(),userExchangeRecordRequest.getEndDate(),userExchangeRecordRequest.getPageNo(),userExchangeRecordRequest.getPageSize());
        return PageResult.success(page, AdminUserExchangeRecordVO.class);
    }
    @PostMapping(value="/updateUserAssets", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "用户积分录入",notes="用户积分录入", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result updateUserAssets(@Valid @RequestBody UpdateUserAssetsRequest request){
        Boolean bl=false;
        if (request.getFlag()){
            bl=userAssetsService.addIntegralByUserId(request.getTokenNum(),request.getUserId(), CoinCategoryEnum.INTEGRAL, AssetChangeLogEnum.ADD_BALANCE_ENTRY,null,"系统赠送");
        }else{
            bl=userAssetsService.subIntegralByUserId(request.getTokenNum(),request.getUserId(), CoinCategoryEnum.INTEGRAL, AssetChangeLogEnum.SUB_BALANCE_ENTRY,null,"系统扣除");
        }
        if (bl){
            GxequityRecords gxequityRecords=new GxequityRecords();
            gxequityRecords.setUserId(request.getUserId());
            gxequityRecords.setFlag(request.getFlag());
            gxequityRecords.setTokenNum(request.getTokenNum());
            gxequityRecords.setReason(request.getReason());
            gxequityRecords.insert();
        }
        return Result.success();
    }




    @PostMapping(value="/batchEnterIntegrationShow")
    @ApiOperation(value = "星球碎片表格解析",notes="批量加减积分展示", httpMethod = "POST")
    public Result<BatchEnterIntegrationShowVO> batchEnterIntegrationShow(@RequestParam(value="file",required=false) MultipartFile file){

        Assert.notNull(file,()->new GlobalRunTimeException("文件不能为空"));

        BatchEnterIntegrationShowVO batchEnterIntegrationShowVO;

        RLock lock = redisson.getLock(RedisKeyEnum.BATCH_ENTER_INTEGRATION.getKey());
        try {
            boolean res = lock.tryLock(10, TimeUnit.SECONDS);
            if (res) {
                batchEnterIntegrationShowVO = userAssetsService.batchEnterIntegrationShow(file);
            }else{
                return Result.fail("请稍后重试!");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new GlobalRunTimeException("系统超时");
        } finally {
            lock.unlock();
        }

        return Result.success(batchEnterIntegrationShowVO);
    }
    @PostMapping(value="/batchAddEnterPoints", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "批量录入积分",notes="批量录入积分", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result<BatchEnterIntegrationShowVO> batchAddEnterPoints(@Valid @RequestBody AdminBatchEnterPointsRequest request){

        RLock lock = redisson.getLock(RedisKeyEnum.BATCH_ENTER_INTEGRATION.getKey());
        try {
            boolean res = lock.tryLock(10, TimeUnit.SECONDS);
            if (res) {
                userAssetsService.batchAddEnterPoints(request.getList(),request.getIsAdd(),request.getReason());
            }else{
                return Result.fail("请稍后重试!");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new GlobalRunTimeException("系统超时");
        } finally {
            lock.unlock();
        }

        return Result.success();
    }


}
